package com.tboss.template.common.advice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.tboss.template.system.service.MappingUserInfoGroupService;

@Component
@Aspect
public class ChangeGroupCheckingAdvice {
 
    /*@Pointcut("within(@org.springframework.stereotype.Controller *)")
    public void controller() {}

    @Pointcut("execution(* *(..))")
    public void methodPointcut() {}

    @Pointcut("within(@org.springframework.web.bind.annotation.RequestMapping *)")
    public void requestMapping() {}

    @Before("controller() && methodPointcut() && requestMapping()")
    public void aroundControllerMethod(JoinPoint joinPoint) throws Throwable {
        System.out.println("Invoked: " + niceName(joinPoint));
    }

    @AfterReturning("controller() && methodPointcut() && requestMapping()")
    public void afterControllerMethod(JoinPoint joinPoint) {
        System.out.println("Finished: " + niceName(joinPoint));
    }

	private String niceName(JoinPoint joinPoint) {
        return joinPoint.getTarget().getClass()
                + "#" + joinPoint.getSignature().getName()
                + "\n\targs:" + Arrays.toString(joinPoint.getArgs());
    }*/

	@Autowired MappingUserInfoGroupService mapUsrInfoGrpService;
	
	@Pointcut("execution(public * com.tboss.template..*Controller.*(..))")
	public void includeController(){}

	@Pointcut("!execution(public * com.tboss.template.home.controller.AuthController.*(..))")
	public void excludeController(){}

	@Around("(includeController() && excludeController()) && target(controller)")
	public Object aroundController(ProceedingJoinPoint joinPoint, Object controller) {
//		ServletRequestAttributes requestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
//		HttpServletRequest request = requestAttributes.getRequest();
//		System.out.println("@@@>>> " + request.getServletPath());
		
		String view = null;
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String uName = null;
		if(auth != null) uName = auth.getName(); 
		try {
			view = (String) joinPoint.proceed();
			
			if(uName != null && !uName.equals("anonymousUser")){
				Integer cnt = this.mapUsrInfoGrpService.checkGrpChgChkField(uName);
				
				if(cnt > 0){
					//view = "template/auth/authConfirm";
					view = "template/auth/redirectionLogin";
				}
			}
			
		} catch (Throwable e) { //e.printStackTrace();
			//org.springframework.validation.support.BindingAwareModelMap cannot be cast to java.lang.String
		}
		
		return view;
	}
	
}